package com.xiaoma.common.observer.single

import android.util.Log
import androidx.lifecycle.LifecycleOwner
import com.xiaoma.common.observer.Observer
import java.util.concurrent.ConcurrentHashMap

/**
 * author: liangjingbo
 * date: 2022/7/1
 * describe: 单数据被观察者，只能收到最后一次发送的数据
 */
open class SingleDataObservable<T> {

    private val TAG = "${this.javaClass.simpleName}Tag"
    private val mWrappers: ConcurrentHashMap<Observer<T>, SingleDataObserverWrapper<T>> =
        ConcurrentHashMap()

    /**
     * 订阅
     * @param owner LifecycleOwner
     * @param isCurResumeReceived Boolean
     * 如果当前本身是 resume 状态时，是否接受事件。true：接受事件，false：不接受事件，但是下次回调 resume 时也不会回调事件
     * @param observer Observer<T> 监听者
     */
    fun observer(
        owner: LifecycleOwner,
        isCurResumeReceived: Boolean = false,
        observer: Observer<T>) {
        val wrapper = SingleDataObserverWrapper(owner, observer, isCurResumeReceived, mWrappers)
        if (mWrappers.containsKey(wrapper.observer)) {
            Log.w(TAG, "observer() Cannot add the same observer !!!")
            return
        }
        mWrappers[wrapper.observer] = wrapper
        owner.lifecycle.addObserver(wrapper)
    }

    open fun dispatchValue(value: T) {
        mWrappers.forEach {
            it.value.setData(value)
        }
    }
}